package com.apes.scm.voucher.service.builder;

import com.apes.scm.account.account.model.InventoryMode;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.service.BusinessType;
import com.apes.scm.voucher.service.VoucherType;
import org.springframework.stereotype.Component;

/**
 * 功能：返厂订单凭证构造器
 *
 * @author xul
 * @create 2018-10-18 9:26
 */
@Component
public class PurchaseReturnVoucherBuilder extends AbstractVoucherBuilder {

    public PurchaseReturnVoucherBuilder() {
        this.voucherType = VoucherType.SUPPLIER_PURCHASE;
        this.BusinessTypes = new String[]{BusinessType.PURCHASE_RETURN};
    }

    /**
     * 功能：创建凭证
     *
     * @param voucher
     */
    @Override
    public Voucher create(Voucher voucher) {
        voucher.setReturned(true);

        if (!("Supplier".equals(voucher.getPartner().getRole().getId()))) {
            throw new RuntimeException("返厂凭证请指定供应角色的合作伙伴[" + voucher.getPartner().getId() + "]!");
        }

        String inventoryMode = voucher.getInventoryMode();
        voucher.getVoucherItems().stream().
                filter(item -> item.getInventoryBatch() != null).
                forEach(item -> {
                    if (!inventoryMode.equals(item.getInventoryBatch().getCooperation().getInventoryMode())) {
                        throw new RuntimeException("批次：" + item.getInventoryBatch().getId() + " 库存方式与返厂单不一致！");
                    }
                });

        /**保存凭证**/
        voucher = save(voucher);

        /**跨公司/公司间交易**/
        crossCompanyTransaction(voucher);

        /**成本核算/价值评估**/
        costing(voucher);

        /**暂估款**/
        changCurrentProvisional(voucher, 1);

        /**账单：用于跨公司内部交易记帐**/
        if (voucher.isInvoiced() && voucher.getInventoryMode().equals(InventoryMode.IM_OWN)) {
            invoiced(voucher);
        }

        return voucher;
    }


}
